/**
 * 待办事项控制器
 * 处理待办事项相关的数据库操作
 */

import { BaseController, ensureDbInit, createResponse, createErrorResponse, createPaginationResponse } from './BaseController'
import database from '../../utils/database'
import { generateId } from '../../mock/utils'

export class TodosController extends BaseController {
  constructor() {
    super('todos')
  }
  
  /**
   * 获取待办事项列表
   */
  async getTodos(params: {
    page?: number
    pageSize?: number
    status?: string
    priority?: string
    categoryId?: string
    dueDate?: string
    keyword?: string
  } = {}) {
    try {
      const {
        page = 1,
        pageSize = 20,
        status,
        priority,
        categoryId,
        dueDate,
        keyword
      } = params
      
      let whereClause = 'is_deleted = 0'
      let whereParams: any[] = []
      
      if (status) {
        whereClause += ' AND status = ?'
        whereParams.push(status)
      }
      
      if (priority) {
        whereClause += ' AND priority = ?'
        whereParams.push(priority)
      }
      
      if (categoryId) {
        whereClause += ' AND category_id = ?'
        whereParams.push(categoryId)
      }
      
      if (dueDate) {
        whereClause += ' AND due_date = ?'
        whereParams.push(dueDate)
      }
      
      if (keyword) {
        whereClause += ' AND (title LIKE ? OR description LIKE ?)'
        whereParams.push(`%${keyword}%`, `%${keyword}%`)
      }
      
      return await this.getList({
        page,
        pageSize,
        where: whereClause,
        whereParams,
        orderBy: 'priority DESC, due_date ASC, created_at DESC'
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取待办事项失败')
    }
  }
  
  /**
   * 创建待办事项
   */
  async createTodo(data: {
    title: string
    description?: string
    priority?: string
    categoryId?: string
    dueDate?: string
    tags?: string[]
    estimatedTime?: number
    reminder?: string
  }) {
    try {
      await ensureDbInit()
      const todoId = generateId()
      const now = new Date().toISOString()
      
      const todoData = {
        id: todoId,
        user_id: 'current_user',
        title: data.title,
        description: data.description || '',
        status: 'pending',
        priority: data.priority || 'medium',
        category_id: data.categoryId || '',
        due_date: data.dueDate || null,
        tags: JSON.stringify(data.tags || []),
        estimated_time: data.estimatedTime || 0,
        actual_time: 0,
        reminder: data.reminder || null,
        completed_at: null,
        created_at: now,
        updated_at: now,
        is_deleted: 0
      }
      
      await database.insert('todos', todoData)
      
      return createResponse({
        id: todoId,
        ...data,
        status: 'pending',
        actualTime: 0,
        createdAt: now,
        updatedAt: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '创建待办事项失败')
    }
  }
  
  /**
   * 更新待办事项
   */
  async updateTodo(id: string, data: any) {
    try {
      await ensureDbInit()
      const updateData = {
        ...data,
        updated_at: new Date().toISOString()
      }
      
      if (updateData.tags) {
        updateData.tags = JSON.stringify(updateData.tags)
      }
      
      const rowsAffected = await database.update(
        'todos',
        updateData,
        'id = ? AND is_deleted = 0',
        [id]
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('待办事项不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '更新待办事项失败')
    }
  }
  
  /**
   * 删除待办事项
   */
  async deleteTodo(id: string) {
    try {
      await ensureDbInit()
      const now = new Date().toISOString()
      
      const rowsAffected = await database.update(
        'todos',
        {
          is_deleted: 1,
          updated_at: now
        },
        'id = ? AND is_deleted = 0',
        [id]
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('待办事项不存在', 1003)
      }
      
      return createResponse({ success: true })
    } catch (error: any) {
      return createErrorResponse(error.message || '删除待办事项失败')
    }
  }
  
  /**
   * 获取待办事项详情
   */
  async getTodoDetail(id: string) {
    return await this.getDetail(id)
  }
  
  /**
   * 完成待办事项
   */
  async completeTodo(id: string) {
    try {
      await ensureDbInit()
      const now = new Date().toISOString()
      
      const rowsAffected = await database.update(
        'todos',
        {
          status: 'completed',
          completed_at: now,
          updated_at: now
        },
        'id = ? AND is_deleted = 0',
        [id]
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('待办事项不存在', 1003)
      }
      
      return createResponse({
        id,
        status: 'completed',
        completedAt: now
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '完成待办事项失败')
    }
  }
  
  /**
   * 取消完成待办事项
   */
  async uncompleteTodo(id: string) {
    try {
      await ensureDbInit()
      const now = new Date().toISOString()
      
      const rowsAffected = await database.update(
        'todos',
        {
          status: 'pending',
          completed_at: null,
          updated_at: now
        },
        'id = ? AND is_deleted = 0',
        [id]
      )
      
      if (rowsAffected === 0) {
        return createErrorResponse('待办事项不存在', 1003)
      }
      
      return createResponse({
        id,
        status: 'pending',
        completedAt: null
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '取消完成待办事项失败')
    }
  }
  
  /**
   * 批量操作待办事项
   */
  async batchUpdateTodos(data: {
    ids: string[]
    action: 'complete' | 'uncomplete' | 'delete' | 'update'
    updateData?: any
  }) {
    try {
      await ensureDbInit()
      const { ids, action, updateData } = data
      
      if (!ids || ids.length === 0) {
        return createErrorResponse('请选择要操作的待办事项', 1001)
      }
      
      const now = new Date().toISOString()
      let successCount = 0
      
      for (const id of ids) {
        try {
          let rowsAffected = 0
          
          switch (action) {
            case 'complete':
              rowsAffected = await database.update(
                'todos',
                {
                  status: 'completed',
                  completed_at: now,
                  updated_at: now
                },
                'id = ? AND is_deleted = 0',
                [id]
              )
              break
              
            case 'uncomplete':
              rowsAffected = await database.update(
                'todos',
                {
                  status: 'pending',
                  completed_at: null,
                  updated_at: now
                },
                'id = ? AND is_deleted = 0',
                [id]
              )
              break
              
            case 'delete':
              rowsAffected = await database.update(
                'todos',
                {
                  is_deleted: 1,
                  updated_at: now
                },
                'id = ? AND is_deleted = 0',
                [id]
              )
              break
              
            case 'update':
              if (updateData) {
                const finalUpdateData = {
                  ...updateData,
                  updated_at: now
                }
                
                if (finalUpdateData.tags) {
                  finalUpdateData.tags = JSON.stringify(finalUpdateData.tags)
                }
                
                rowsAffected = await database.update(
                  'todos',
                  finalUpdateData,
                  'id = ? AND is_deleted = 0',
                  [id]
                )
              }
              break
          }
          
          if (rowsAffected > 0) {
            successCount++
          }
        } catch (error) {
          // 单个操作失败不影响其他操作
          console.error(`批量操作待办事项 ${id} 失败:`, error)
        }
      }
      
      return createResponse({
        total: ids.length,
        success: successCount,
        failed: ids.length - successCount
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '批量操作待办事项失败')
    }
  }
  
  /**
   * 获取待办事项统计
   */
  async getTodoStats(params: {
    startDate?: string
    endDate?: string
    categoryId?: string
  } = {}) {
    try {
      await ensureDbInit()
      const { startDate, endDate, categoryId } = params
      
      let whereClause = 'is_deleted = 0'
      let whereParams: any[] = []
      
      if (categoryId) {
        whereClause += ' AND category_id = ?'
        whereParams.push(categoryId)
      }
      
      if (startDate) {
        whereClause += ' AND created_at >= ?'
        whereParams.push(startDate)
      }
      
      if (endDate) {
        whereClause += ' AND created_at <= ?'
        whereParams.push(endDate)
      }
      
      // 总数统计
      const totalResult = await database.query(
        `SELECT COUNT(*) as total FROM todos WHERE ${whereClause}`,
        whereParams
      )
      
      if (totalResult.code !== 0) {
        return createErrorResponse(totalResult.message || '查询总数失败')
      }
      
      // 按状态统计
      const statusResult = await database.query(
        `SELECT 
          status,
          COUNT(*) as count
        FROM todos 
        WHERE ${whereClause}
        GROUP BY status`,
        whereParams
      )
      
      if (statusResult.code !== 0) {
        return createErrorResponse(statusResult.message || '查询状态统计失败')
      }
      
      // 按优先级统计
      const priorityResult = await database.query(
        `SELECT 
          priority,
          COUNT(*) as count
        FROM todos 
        WHERE ${whereClause}
        GROUP BY priority`,
        whereParams
      )
      
      if (priorityResult.code !== 0) {
        return createErrorResponse(priorityResult.message || '查询优先级统计失败')
      }
      
      // 逾期统计
      const overdueResult = await database.query(
        `SELECT COUNT(*) as count FROM todos 
        WHERE ${whereClause} AND due_date < date('now') AND status != 'completed'`,
        whereParams
      )
      
      if (overdueResult.code !== 0) {
        return createErrorResponse(overdueResult.message || '查询逾期统计失败')
      }
      
      const totalData = totalResult.data || []
      const statusData = statusResult.data || []
      const priorityData = priorityResult.data || []
      const overdueData = overdueResult.data || []
      
      const total = (totalData[0] && typeof totalData[0].total !== 'undefined') ? totalData[0].total : 0
      const overdue = (overdueData[0] && typeof overdueData[0].count !== 'undefined') ? overdueData[0].count : 0
      
      // 格式化状态统计
      const statusStats = {
        pending: 0,
        completed: 0,
        cancelled: 0
      }
      
      statusData.forEach((item: any) => {
        if (item.status && typeof item.count !== 'undefined') {
          statusStats[item.status as keyof typeof statusStats] = item.count
        }
      })
      
      // 格式化优先级统计
      const priorityStats = {
        high: 0,
        medium: 0,
        low: 0
      }
      
      priorityData.forEach((item: any) => {
        if (item.priority && typeof item.count !== 'undefined') {
          priorityStats[item.priority as keyof typeof priorityStats] = item.count
        }
      })
      
      return createResponse({
        total,
        overdue,
        completionRate: total > 0 ? Math.round((statusStats.completed / total) * 100) : 0,
        statusStats,
        priorityStats
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取待办事项统计失败')
    }
  }
  
  /**
   * 获取今日待办事项
   */
  async getTodayTodos() {
    try {
      const today = new Date().toISOString().split('T')[0]
      
      return await this.getTodos({
        dueDate: today,
        page: 1,
        pageSize: 100
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取今日待办事项失败')
    }
  }
  
  /**
   * 获取逾期待办事项
   */
  async getOverdueTodos(params: {
    page?: number
    pageSize?: number
  } = {}) {
    try {
      const { page = 1, pageSize = 20 } = params
      const today = new Date().toISOString().split('T')[0]
      
      const whereClause = 'is_deleted = 0 AND due_date < ? AND status != ?'
      const whereParams = [today, 'completed']
      
      return await this.getList({
        page,
        pageSize,
        where: whereClause,
        whereParams,
        orderBy: 'due_date ASC, priority DESC'
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '获取逾期待办事项失败')
    }
  }
  
  /**
   * 搜索待办事项
   */
  async searchTodos(params: {
    keyword: string
    page?: number
    pageSize?: number
    status?: string
    priority?: string
  }) {
    try {
      const { keyword, page = 1, pageSize = 20, status, priority } = params
      
      if (!keyword || keyword.trim() === '') {
        return createErrorResponse('搜索关键词不能为空', 1001)
      }
      
      let whereClause = 'is_deleted = 0 AND (title LIKE ? OR description LIKE ?)'
      let whereParams: any[] = [`%${keyword}%`, `%${keyword}%`]
      
      if (status) {
        whereClause += ' AND status = ?'
        whereParams.push(status)
      }
      
      if (priority) {
        whereClause += ' AND priority = ?'
        whereParams.push(priority)
      }
      
      return await this.getList({
        page,
        pageSize,
        where: whereClause,
        whereParams,
        orderBy: 'priority DESC, due_date ASC, created_at DESC'
      })
    } catch (error: any) {
      return createErrorResponse(error.message || '搜索待办事项失败')
    }
  }
}

// 导出单例实例
export const todosController = new TodosController()